package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.entity.PageResult;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Role;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

//以下为新增
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);



        //条件查询套餐集合
        List<Setmeal> list = userMapper.findByCondition(queryString);

        PageInfo<Setmeal> pageInfo = new PageInfo<>(list);

        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public List<Role> findAllRole() {
        return userMapper.findAllRole();
    }

    @Override
    public void add(Integer[] roleIds, User user) {
        //新增数据插入到t_user
        userMapper.add(user);

        //新增t_user_role数据
        setUserAndRole(roleIds,user.getId());
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        return userMapper.findRoleIdsByUserId(id);
    }

    @Override
    public void edit(Integer[] roleIds, User user) {
        //通过用户的中间表数据
        deleteAssociation(user.getId());
        //重新插入中间表数据
        setUserAndRole(roleIds,user.getId());
        //更新用户数据
        userMapper.edit(user);

    }
//删除中间表数据
    private void deleteAssociation(Integer id) {
        userMapper.deleteAssociation(id);
    }

    @Override
    public Integer testUsername(String username) {

        return userMapper.testUsername(username);
    }

    @Override
    public void deleteById(Integer id) {
//        删除中间表数据
        deleteAssociation(id);
//        删除用户数据
        userMapper.daleteById(id);
    }

    private void setUserAndRole(Integer[] roleIds, Integer id) {
        if (roleIds!=null && roleIds.length>0){
            //将添加检查组和检查项的中间表数据
            userMapper.setUserAndRole(roleIds,id);

        }
    }
}
